from __future__ import with_statement
import positioning
import sysinfo
import appuifw
import sys
import e32
from time import localtime, strftime
import btsocket
import location
import os
import ConfigParser

APP_NAME = 'YouLoc'
APP_VERSION = 0.4

"""
Tero Heino, whiz@iki.fi, 2009
"""


class YouLoc:
	cfg_file = 'e:\\youloc.cfg'
	config = None
	t = None
	lock = None
	apo = None
	apid = None
	fix = False
	position_data = None
	previous_position_data = None
	gsm_cell = None
	
	def __init__ (self):
		self.config = ConfigParser.RawConfigParser()
		
		self.lock = e32.Ao_lock()
		appuifw.app.exit_key_handler = self.quit
		self.t = appuifw.Text()
		appuifw.app.body = self.t
		self.t.clear()

	def init_ui(self):
		appuifw.app.title = u'%s v%.1f' % (APP_NAME, APP_VERSION)
		appuifw.app.screen = 'large'
		appuifw.app.menu = [(u"Run configure", self.configure),(u"Quit", self.quit)]
		
	def read_config(self):
		if ( os.path.isfile(self.cfg_file) ):
			self.config.read(self.cfg_file)
			self.userkey = self.config.get('common', 'userkey') 
			self.apid = self.config.getint('common', 'apid')
			if self.userkey == None or self.apid == None:
				self.configure()
			self.output(self.userkey)
			self.output(self.apid)
		else:
			self.configure()

	def configure(self):
		apid = None
		userkey = None
		
		apid = btsocket.select_access_point()
		auth_methods = [u"IMEI",u"USERKEY"]
		
		auth_method = appuifw.selection_list(choices=auth_methods , search_field=0)
		if auth_method == 0:
			userkey = unicode(sysinfo.imei())
		elif auth_method == 1:
			while userkey == None:
				userkey = appuifw.query(u"Your YouLoc userkey", "text")
		try:
			self.config.add_section('common')
			self.config.set('common', 'userkey', userkey)
			self.config.set('common', 'apid', apid)
			with open(self.cfg_file, 'wb') as configfile:
			    self.config.write(configfile)
			
		except IOError, e:
			appuifw.note( u'Unable to write to file!', 'error' )
			
		self.apid = apid
		self.userkey = userkey
		
	def get_internets(self):
		
		self.apo = btsocket.access_point(self.apid)

	def get_satellites(self):
		positioning.set_requestors([{"type":"service", "format":"application", "data":"YouLoc"}])
		positioning.position(	course=1,
								satellites=0,
								callback=self.processLocationData,
								interval=1000000,
								partial=1)
		

	def output(self, msg, clearscreen = False):
		""" Output formatted message wit"""
		if clearscreen:
			self.t.clear()
			self.t.add(u"%s\n--------\n" % strftime("%H:%M:%S", localtime() ) )
		self.t.add(u"%s\n" % msg)


	def run(self):
		self.read_config()
		self.init_ui()
		self.get_internets()
		self.get_satellites()
		self.output('%s v%.1f' % (APP_NAME, APP_VERSION))
		self.output("connecting..")
		while True:
			self.lock.wait()
	
		self.output(u"Finished..")

	def has_fix(self):
		if self.position_data:
			data = self.position_data
			if "position" in data:
				if str(data['position'].get('latitude', 'nan')).lower() != "nan":
					return True
 		return False

# latitude altitude vertical_accuracy longitude horizontal_accuracy

	def processLocationData(self, data):
		self.position_data = data
		self.fix = self.has_fix()
		self.gsm_cell = location.gsm_location()
		
		if self.fix:
			self.postData()
			#self.t.add(u"%s\n\n%s\n\n" % ( self.position_data["position"], self.position_data["course"]) )
		

     

	def postData(self):
		btsocket.set_default_access_point(self.apo)
		host = "youloc.net"
		port = 80
		lat = self.position_data['position']['latitude']
		lon = self.position_data['position']['longitude']
		alt = self.position_data['position']['altitude']
		speed = self.position_data['course']['speed']
		if self.previous_position_data != None:
			if "%.4f" % lat == "%.4f" % self.previous_position_data['position']['latitude'] and "%.4f" % lon == "%.4f" % self.previous_position_data['position']['longitude']:
				return
			
		url = "/logger.php?userkey=%s&lat=%s&lon=%s&alt=%s&speed=%s" % (self.userkey, lat, lon, alt, speed)
		if self.gsm_cell != None:
			mcc = self.gsm_cell[0]
			mnc = self.gsm_cell[1]
			lac = self.gsm_cell[2]
			cid = self.gsm_cell[3]
			url = "/logger.php?userkey=%s&lat=%s&lon=%s&alt=%s&speed=%s&cell=%s&mcc=%s&mnc=%s&lac=%s" % (self.userkey, lat, lon, alt, speed, cid, mcc, mnc, lac)
			
		s = btsocket.socket(btsocket.AF_INET, btsocket.SOCK_STREAM)
		s.connect( (host, port) )
		s.send("GET %s HTTP 1.1\nHost: %s\n\n" % (url, host))
		s.close()
		
		self.output("Latitude: %.2f\nLongitude: %.2f\nAltitude: %d\nSpeed: %d\n\n" % (lat,lon,alt,speed), True)
		if self.gsm_cell != None:
			self.output("CellID: %d\nMCC: %d\nMNC: %d\nLAC: %d\n" %(cid, mcc, mnc, lac))
        
		self.previous_position_data = self.position_data
        
	    
	def quit (self):
		self.lock.signal()
		appuifw.app.set_exit()
		
				
			
			
if __name__ == "__main__":
	YL = YouLoc()
	YL.run()
